package com.fantasy.servlet;

import com.fantasy.entity.Comment;
import com.fantasy.entity.User;
import com.fantasy.service.CommentService;
import com.fantasy.service.UserService;
import com.fantasy.service.impl.CommentServiceImpl;
import com.fantasy.service.impl.UserServiceImpl;
import com.google.gson.Gson;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/client/comment.do")
public class CommentServlet extends BaseServlet{
    private CommentService commentService=new CommentServiceImpl();
    private UserService userService=new UserServiceImpl();

    /**
     * 添加评论
     * @param request
     * @param response
     * @throws IOException
     */
    public void insertVideoComment(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int videoId = Integer.parseInt(request.getParameter("videoId"));
        int userId = Integer.parseInt(request.getParameter("userId"));
        User user = userService.queryById(userId);
        String comment = request.getParameter("comment");
        String commentReplace = comment.replaceAll("大爷", "真帅");
        int insert = commentService.insert(new Comment(user.getName(), videoId, commentReplace));
        if (insert==1){
            response.getWriter().write("1");
        }else {
            response.getWriter().write("0");
        }
    }

    /**
     * 查询视频评论
     * @param request
     * @param response
     * @throws IOException
     */
    public void videoComment(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int videoId = Integer.parseInt(request.getParameter("videoId"));
        List<Comment> comments = commentService.queryVideoComment(videoId);
        Gson gson=new Gson();
        String commentsJson = gson.toJson(comments);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(commentsJson);
    }
}
